package com.softeng.network.chess;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Vector;


public class Server implements Runnable
{
	private static final int PORT = 4444;
	
	private ServerSocket socket;
	
	private HashMap<String, ObjectOutputStream> clientList = new HashMap<String, ObjectOutputStream>();
	
	private int maxConnections = 2;
	
	private int currentConnections = 0;
	
	private ServerHandler sh1;
	
	private ServerHandler sh2;
	
	private Vector<String> actions = new Vector<String>();
	
	public Server()
	{
		try 
		{
			socket = new ServerSocket(PORT);
		
			Thread t = new Thread(this);
			t.start();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	@Override
	public void run()
	{	
		try 
		{
			while( currentConnections < maxConnections )
			{
				System.out.println( "[SERVER] - " + currentConnections );
				System.out.println( "[SERVER] - Waiting for a client connection..." );
				
				Socket clientSocket = socket.accept();
				
				if( clientSocket != null)
				{
					currentConnections++;
				}
				
				if( currentConnections == 1 )
				{
					sh1 = new ServerHandler( clientSocket, this );
					
					Thread t = new Thread(sh1);
					t.start();
				}
				else if( currentConnections == 2 )
				{
					sh2 = new ServerHandler( clientSocket, this );
					
					Thread t = new Thread(sh2);
					t.start();
				}
				
			}
			
			System.out.println( "left while" );
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	public void pushAction( String action )
	{
		actions.add( action );
	}
	
	public Vector<String> getActions()
	{
		return actions;
	}
	
	public void removeAction( String cmd )
	{
		actions.remove( cmd );
	}

}
